import { getme } from '@/api/user'
import options from './options'
import bus from '@/utils/bus'

export default options({
  state: {
    user: null,
  },
  mutations: {
    setUser(state, user) {
      state.user = user
      bus.$emit('setUser', user)
    },
    setToken(state, token) {
      localStorage.setItem('TOKEN', token)
    },
    outLogin(state) {
      localStorage.removeItem('TOKEN')
      state.user = null
    },
  },
  actions: {
    async sendMe({ commit }) {
      const data = await getme()
      if (data.code !== 200) return localStorage.removeItem('TOKEN')
      commit('setUser', data.user)
      return data.user
    },
    async login({ commit, dispatch }, token) {
      console.log(token)
      localStorage.setItem('TOKEN', token)
      return await dispatch('sendMe')
    },
  },
  getters: {
    portrait(state) {
      if (!state.user) return '/image/default.jpg'
      return '/image/' + (state.user.portrait || 'default.jpg')
    },
    username(state) {
      if (!state.user) return ''
      return state.user.username
    },
    mail(state) {
      if (!state.user) return ''
      return state.user.mail
    },
    power(state) {
      if (!state.user) return []
      return state.user.power
    },
  },
})
